﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.Design;
using System.ComponentModel;
using System.Collections;
using System.Drawing.Design;
using Water.Util;

namespace Water.Web.Controls.Office.Excel
{
    [ToolboxItem(false)]
    [ParseChildren(true)]
    [ToolboxData("<{0}:Sheet runat=server></{0}:Sheet>")]
    public partial class Sheet:DataBoundControl//Control
    {
        private string tilte;
        private int row=1;
        private int col=1;
        private string tableHeaderStyle="header";
        private string tableFooterStyle;
        private string tableCellStyle="cell";
        private bool createTableHeader=true;
        private LabelItemCollection labels;
        private ColumnItemCollection columns;
        private string LIST_FIELD_KEY;
        private int sheetNum;
        private string dataSessionId;

        protected internal int SheetNum
        {
            get { return sheetNum; }
            set { sheetNum = value; }
        }

        private Util.TableType tableType=Util.TableType.Table;
        private bool isChart = false;


        public override void RenderBeginTag(HtmlTextWriter writer)
        {
            //base.RenderBeginTag(writer);
        }
        public override void RenderEndTag(HtmlTextWriter writer)
        {
            //base.RenderEndTag(writer);
        }

        [Browsable(true), Category("Behavior"), GlobalizeDescription("SheetTilte")]
        public string Tilte
        {
            get { return Water.Web.Prompt.PromptProxy.GetPromptDesc(tilte); }
            set { tilte = value; }
        }

        [Browsable(true), Category("Behavior"), GlobalizeDescription("Row")]
        public int Row
        {
            get { return row; }
            set { row = value; }
        }

        [Browsable(true), Category("Behavior"), GlobalizeDescription("Col")]
        public int Col
        {
            get { return col; }
            set { col = value; }
        }

        [Browsable(true), Category("Data"), GlobalizeDescription("Items"), NotifyParentProperty(true), TypeConverter(typeof(CollectionConverter))]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public LabelItemCollection Labels
        {
            get 
            {
                if (this.labels == null)
                    this.labels = new LabelItemCollection();
                return labels; 
            }
            set { labels = value; }
        }
        [Browsable(true), Category("Data"), GlobalizeDescription("Items"), NotifyParentProperty(true), TypeConverter(typeof(CollectionConverter))]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public ColumnItemCollection Columns
        {
            get 
            {
                if (this.columns == null)
                    this.columns = new ColumnItemCollection();
                return columns; 
            }
            set { columns = value; }
        }

        [Browsable(true), Category("Appearance"), GlobalizeDescription("TableHeaderStyle"),DefaultValue("header")]
        public string TableHeaderStyle
        {
            get { return tableHeaderStyle; }
            set { tableHeaderStyle = value; }
        }
        [Browsable(true), Category("Appearance"), GlobalizeDescription("TableFooterStyle")]
        public string TableFooterStyle
        {
            get { return tableFooterStyle; }
            set { tableFooterStyle = value; }
        }
        [Browsable(true), Category("Appearance"), GlobalizeDescription("TableCellStyle"),DefaultValue("cell")]
        public string TableCellStyle
        {
            get { return tableCellStyle; }
            set { tableCellStyle = value; }
        }
        [Browsable(true), Category("Behavior"), GlobalizeDescription("CreateTableHeader"),DefaultValue(true)]
        public bool CreateTableHeader
        {
            get { return createTableHeader; }
            set { createTableHeader = value; }
        }
        [Browsable(true), Category("Behavior"), GlobalizeDescription("TableType"), DefaultValue(Util.TableType.Table)]
        public Util.TableType TableType
        {
            get { return tableType; }
            set { tableType = value; }
        }
        [Browsable(true), Category("Behavior"), GlobalizeDescription("IsChart"), DefaultValue(false)]
        public bool IsChart
        {
            get { return isChart; }
            set { isChart = value; }
        }


        public virtual void RenderControl(HtmlTextWriter writer,int sheetNum)
        {
            this.sheetNum = sheetNum;
            this.RenderControl(writer);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            this.LIST_FIELD_KEY = this.Context.Request.FilePath.Replace("/", "$").Replace(".aspx", "") + "$";

            string _absoluteUrl = this.Context.Request.Url.AbsoluteUri;

            _absoluteUrl=_absoluteUrl.Replace(StringUtil.EXCELREPORT, StringUtil.GETTEXTDATA);
            _absoluteUrl += ("&" + StringUtil.DATASESSIONID+"="+this.dataSessionId);

            Util.QueryTable _queryTablle = new Util.QueryTable(this.sheetNum, this);

            if (Columns != null && Columns.Count > 0)
            {
                //create new sheet
                writer.Write(Util.Sheet.CreateNewSheet(this.sheetNum, this.Tilte));
                //create querytable
                writer.Write(_queryTablle.CreateQueryTable(_absoluteUrl, this.str_dataTypes));
                //create table cell style
                if(!string.IsNullOrEmpty(this.TableCellStyle))
                    writer.Write(_queryTablle.CreateTabelCellStyle(this.TableCellStyle));
                //create table header style
                if (!string.IsNullOrEmpty(this.TableHeaderStyle) && this.CreateTableHeader)
                    writer.Write(_queryTablle.CreateTabelHeadStyle(this.TableHeaderStyle));
                if (!string.IsNullOrEmpty(this.TableFooterStyle))
                    writer.Write(_queryTablle.CreateTableFooterStyle(this.TableFooterStyle));
                //create column(comput、foorer text etc...)
                writer.Write(_queryTablle.CreateColumns(Columns));
            }
            if (Labels != null && Labels.Count > 0)
            {
                foreach (Label _label in Labels)
                {
                    if (0 == _label.OffsetRow)
                        _label.Render(writer);
                    else
                        _label.Render(writer, _queryTablle, _label.OffsetRow);
                }
            }

            if (this.TableType == Util.TableType.PivotTable)
                writer.Write(_queryTablle.CreatePivotTable(this.Columns));

            base.Render(writer);
        }

        private string str_dataTypes =string.Empty;
        private List<string> list_fields = new List<string>();
        private string str_heads = string.Empty;


        private void InitColumns()
        {
            if (Columns != null && Columns.Count > 0)
            {
                StringBuilder sb_dataTypes = new StringBuilder();
                StringBuilder sb_tableHeader = new StringBuilder();
                int i=0;
                foreach (Column _col in Columns)
                {
                    sb_dataTypes.Append(_col.DataType + ",");
                    list_fields.Add(_col.DataField);
                    if (this.CreateTableHeader)
                    {
                        sb_tableHeader.Append(_col.HeaderText.Replace(Water.Util.Convert.SEPARATOR_CHAR, "").Replace(Water.Util.Convert.NEWLINE_CHAR, ""));
                        i++;
                        if (Columns.Count != i)
                            sb_tableHeader.Append(Water.Util.Convert.SEPARATOR_CHAR);
                    }
                }
                if (this.CreateTableHeader)
                {
                    sb_tableHeader.Append(Water.Util.Convert.NEWLINE_CHAR);
                    str_heads = sb_tableHeader.ToString();
                }


                str_dataTypes = sb_dataTypes.ToString();
                str_dataTypes = str_dataTypes.Substring(0, str_dataTypes.Length - 1);
            }
        }
        protected override void PerformDataBinding(IEnumerable data)
        {
            if (PageState.State == StringUtil.EXCELREPORT)
            {
                InitColumns();
                if (null != data)
                {
                    string _text=string.Empty;
                    if (this.CreateTableHeader&& !string.IsNullOrEmpty(str_heads))
                    {
                        _text += str_heads;
                    }
                    _text += Water.Util.Convert.ToTextFromIEnumerable(data, list_fields);
                    this.dataSessionId =Guid.NewGuid().ToString().Replace("-","").ToUpper();

                    this.Page.Application[this.dataSessionId]= _text;

                }
            }
        }

    }
}
